<?php
namespace app\index\controller;

use think\facade\Cache;

class Index extends Base
{
    public function index()
    {
        //获取学生总数
        $stu_count = \app\index\model\Student::count();
        $this->assign('stu_count', $stu_count);
        $scoreModel = new \app\index\model\Score();
        $perfect_count = $scoreModel->where("score", "=", 100)->count();
        $this->assign('perfect_count', $perfect_count);

        $nine_count = $scoreModel->where("score", ">=", 90)->count();
        $this->assign('nine_count', $nine_count);

        $bad_count = $scoreModel->where("score", "<", 60)->count();
        $this->assign('bad_count', $bad_count);

        //获取所有成绩排行
        $rank = $scoreModel->getScoreRank();
        $this->assign('rank', $rank);
        return $this->fetch();
    }

    /**
     * 登录
     * @return mixed
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');

            $data = [
                'username' => $username,
                'password' => $password
            ];
            $result = $this->validate($data, 'app\index\validate\Member.login');

            if ($result !== true) {
                $this->error($result);
            }

            $member = (new \app\index\model\Member)->login($data);

            if ($member === false) {
                $this->error('账号或密码不正确');
            }
            session('uid', $member['id']);
            session('userinfo', $member);
            $this->redirect(url('index'));
        }
        return $this->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        session('uid', 0);
        //Cache::store('redis')->clear();
        $this->redirect('login');
    }
}
